<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Loader;
use think\Request;
use think\Validate;
use think\cache\driver\Redis;
use app\common\model\GoodsSpecificationSku;
/**
 * 购物车
 */
class Cart extends Api {
    protected $noNeedLogin = [''];//空代表都需要验证
    protected $noNeedRight = ['*'];

    /**
    添加购物车
     *
     */
    public function addGoods(){

        $userId = $this->auth->id;
        $goods_id=input('goods_id');
        $sku_id=input('sku_id');
        $buy_num=input('buys_num');
        if (!$goods_id&&!$sku_id&&!$buy_num){
            $this->error('参数不完整');
        }
        if($buy_num<=0){

            $this->error('数量不可为0');
        }
        //判断购物车的商品数量是否超过实际商品熟练
        $skuInfo=GoodsSpecificationSku::get(['id'=>$sku_id,'goods_id'=>$goods_id]);
        if (empty($skuInfo)){

            $this->error('无效的规格');

        }
        if ($skuInfo['deletetime']!=null){

            $this->error('当前商品规格已删除，请刷新');
        }
        if ($skuInfo['stock']<$buy_num){
            $this->error('库存不足');
        }
        $Cache=new Redis();
        $redis = $Cache->handler();
        $redis_key='szshop_cart_'.$userId;
        $hash_key = $goods_id . '_' . $sku_id;
        if ($redis->hexists($redis_key, $hash_key)) {//判断是否之前添加过
            $redis->hincrby($redis_key, $hash_key, $buy_num);
            if ($redis->hget($redis_key, $hash_key) == 0) {
                $redis->hdel($redis_key, $hash_key);
            }
        } else {
            $redis->hset($redis_key, $hash_key, $buy_num);
        }
        $this->success('请求成功!', null);
    }
    /**
     * 获取购物车数据
     */
    public function getShopCart(){
        $userId = $this->auth->id;
        $Cache=new Redis();
        $redis = $Cache->handler();

        $redis_key = 'szshop_cart_' .$userId;
        $goods_info =array_reverse($redis->hkeys($redis_key));
        if (empty($goods_info)){
            $this->success('请求成功!', ['list'=>[]]);
        }
        $spec_count_map = [];
        $spec_ids = [];
        foreach ($goods_info as $keys => $values) {
            $g_con = explode('_', $values);
            $goods_id = $g_con[0];
            $sku_id = $g_con[1];
            $buys_num = $redis->hget($redis_key, $values);
            $ret[$keys]['goods_id'] = $goods_id;
            $ret[$keys]['sku_id'] = $sku_id;
            $ret[$keys]['buys_num'] = $buys_num;
            $spec_count_map[$sku_id] = $buys_num;
            $spec_ids[] = $sku_id;
        }
        //获取商品信息
        $goodsSku=new GoodsSpecificationSku();
        $goodsList=$goodsSku->getCartGoodsList($spec_ids);
        if (empty($goodsList)){
            $this->success('请求成功!', ['list'=>[]]);
        }
        $goods_ids = assoc_unique($ret, 'goods_id');
        $goods_ids_arr=array_column($goods_ids,'goods_id');//二维数组转一维数组

        $goodsModel= model('app\common\model\Goods');
//        $shop_ids=$goodsModel->whereIn('id',$goods_ids_arr)->select();//查询商家
////        foreach ($shop_ids as $row) {
////            $row->visible(['id', 'merchant_id']);
////            $row->visible(['admin']);
////            $row->getRelation('admin')->visible(['nickname']);
////        }
//        $shop_ids=toArray($shop_ids);
//
//        $shop_ids = assoc_unique($shop_ids, 'merchant_id');
//        dump($shop_ids);
        // 购买数量
      //  foreach ($shop_ids as $k=>$v){
            foreach ($goodsList as $key => &$goods) {
                $goodsList[$key]['buy_num'] = $spec_count_map[$goods['id']];
                $goodsList[$key]['thumbnail_image']=get_app_image_url($goods['thumbnail_image']);
                $goodsList[$key]['all_price']=$goods['current_price']*$goods['buy_num'];
            }
      //  }
//        dump($argv);
//        die();
        $this->success('请求成功!', ['list'=>$goodsList]);

    }
    /**
     * 修改购物车商品数量
     */
    public function updateCartNum(){

        $userId = $this->auth->id;
        $goods_id=input('goods_id');
        $sku_id=input('sku_id');
        $buy_num=input('buys_num');
        if (!$goods_id&&!$sku_id&&!$buy_num){

            $this->error('参数不完整');
        }
        if ($buy_num<=0){

            $this->error('数量不可为0');
        }

        $Cache=new Redis();
        $redis = $Cache->handler();
        $redis_key='szshop_cart_'.$userId;
        $hash_key = $goods_id . '_' . $sku_id;
        $redis->hset($redis_key, $hash_key, $buy_num);
        $this->success('请求成功!', null);
    }
    /**
     * 删除购物车
     */
    public function delShopCart(){
        $userId = $this->auth->id;
        $sku_ids=input('sku_ids');

        $Cache=new Redis();
        $redis = $Cache->handler();
        $redis_key='szshop_cart_'.$userId;

        $goods_info =array_reverse($redis->hkeys($redis_key));
        foreach ($goods_info as $keys => $values) {
            $g_con = explode('_', $values);
            $goods_id = $g_con[0];
            $sku_id = $g_con[1];
            $sku_arr=explode(',',$sku_ids);
            foreach ($sku_arr as $ke=>$va){
                if ($sku_id==$va){
                    $hash_key = $goods_id . '_' . $sku_id;
                    $redis->hdel($redis_key, $hash_key);
                }
            }

        }
        $this->success('请求成功!', []);

    }
    /*
     * 购物车种类数量
     * */
    public function CartNum(){
        $num = $this->cart_num();

        $this->success('请求成功!', ['num'=>$num]);
    }
    /*
     * 获取数量
     * */
    public function cart_num(){
        $userId = $this->auth->id;
        if(!$userId){
           return '';
        }
        $Cache=new Redis();
        $redis = $Cache->handler();
//        $redis_key= $type==2?'shop_cart_'.$userId.'is_checking':'shop_cart_'.$userId;
        $redis_key= 'szshop_cart_'.$userId;

        $goods_info = array_reverse($redis->hkeys($redis_key));
        return  count($goods_info);
    }
}